package com.xywh.emergency_outbound.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.xywh.emergency_outbound.R;
import com.xywh.emergency_outbound.di.component.DaggerMainComponent;
import com.xywh.emergency_outbound.di.module.MainModule;
import com.xywh.emergency_outbound.mvp.contract.MainContract;
import com.xywh.emergency_outbound.mvp.presenter.MainPresenter;
import com.xywh.emergency_outbound.mvp.ui.adapter.MyViewPagerAdapter;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.majiajie.pagerbottomtabstrip.NavigationController;
import me.majiajie.pagerbottomtabstrip.PageNavigationView;
import me.majiajie.pagerbottomtabstrip.SpecialTab;
import me.majiajie.pagerbottomtabstrip.SpecialTabRound;
import me.majiajie.pagerbottomtabstrip.item.BaseTabItem;
import me.majiajie.pagerbottomtabstrip.listener.OnTabItemSelectedListener;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ACTIVITY_MAIN)
public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View {

    public LocationClient mLocationClient = null;
    private ViewPager viewPager;
    private MyLocationListener myListener = new MyLocationListener();


    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMainComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .mainModule(new MainModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_main; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        PageNavigationView tab = (PageNavigationView) findViewById(R.id.tab);

        NavigationController navigationController = tab.custom()
                .addItem(newItem(R.drawable.tab_001_normal, R.drawable.tab_001_selected, "物资调拨"))
                .addItem(newItem(R.drawable.tab_002_normal, R.drawable.tab_002_selected, "调拨订单"))
                .addItem(newItem(R.drawable.tab_003_normal, R.drawable.tab_003_selected, "购物车"))
                .addItem(newItem(R.drawable.tab_004_normal, R.drawable.tab_004_selected, "常用收货地址"))
//                .addItem(newItem(R.drawable.tab_005_normal, R.drawable.tab_005_selected, "我的"))
                .build();

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        viewPager.setAdapter(new MyViewPagerAdapter(getSupportFragmentManager(), navigationController.getItemCount()));
        viewPager.setOffscreenPageLimit(4);

        navigationController.setupWithViewPager(viewPager);
        navigationController.addTabItemSelectedListener(new OnTabItemSelectedListener() {
            @Override
            public void onSelected(int index, int old) {
                //
                //                if (index == 3) {
                //
                //                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                //                    startActivity(intent);
                //                }
            }

            @Override
            public void onRepeat(int index) {
                //                if (index == 3) {
                //
                //                    Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                //                    startActivity(intent);
                //                }
            }
        });

        initBaiDuLocation();
    }

    private BaseTabItem newItem(int drawable, int checkedDrawable, String text) {
        SpecialTab mainTab = new SpecialTab(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        mainTab.setTextDefaultColor(Color.parseColor("#000000"));
        mainTab.setTextCheckedColor(Color.parseColor("#006569"));
        return mainTab;
    }

    private void initBaiDuLocation() {
        //BDAbstractLocationListener为7.2版本新增的Abstract类型的监听接口
        //原有BDLocationListener接口暂时同步保留。具体介绍请参考后文第四步的说明
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);

        //可选，是否需要地址信息，默认为不需要，即参数为false
        //如果开发者需要获得当前点的地址信息，此处必须为true
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认GCJ02
        //GCJ02：国测局坐标；
        //BD09ll：百度经纬度坐标；
        //BD09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回WGS84类型坐标

        option.setScanSpan(10000);
//        option.setScanSpan(60000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true


        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，V7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明


        mLocationClient.start();
        //mLocationClient为第二步初始化过的LocationClient对象
        //调用LocationClient的start()方法，便可发起定位请求
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
    }

    @Subscriber(tag = "setCurrentTab", mode = ThreadMode.MAIN)
    public void setCurrentTab(int position) {
        viewPager.setCurrentItem(position);
    }


    private BaseTabItem newRoundItem(int drawable, int checkedDrawable, String text) {
        SpecialTabRound mainTab = new SpecialTabRound(this);
        mainTab.initialize(drawable, checkedDrawable, text);
        mainTab.setTextDefaultColor(getResources().getColor(R.color.public_white));
        mainTab.setTextCheckedColor(getResources().getColor(R.color.public_white));
        return mainTab;
    }

//    public void setCurrentItem(int index) {
//        viewPager.setCurrentItem(index);
//    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Subscriber(tag = BaseConstants.SET_CURRENT_ITEM, mode = ThreadMode.MAIN)
    public void setCurrentItem(int index) {
        viewPager.setCurrentItem(index);
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                double latitude = location.getLatitude();    //获取纬度信息
                double longitude = location.getLongitude();    //获取经度信息
                float radius = location.getRadius();    //获取定位精度，默认值为0.0f

                String coorType = location.getCoorType();
                //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准

                int errorCode = location.getLocType();
                //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
                mSharedPreferencesHelper.putString(BaseConstants.LAT, String.valueOf(latitude));
                mSharedPreferencesHelper.putString(BaseConstants.LNG, String.valueOf(longitude));
                EventBus.getDefault().post(location, "setAddress");
//                tvl.setText(location.getAddrStr());
                LogUtils.debugEInfo("onReceiveLocation==" + location.getAddrStr());
            }//此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
                // 离线定位成功
                Log.i("baidu_location_result", "offline location success");
                double lat = location.getLatitude();
                double lon = location.getLongitude();
//                tv_location.setText("lat=" + lat + " lon=" + lon);
//                showMessage("lat=" + lat + " lon" + lon);
//                EventBus.getDefault().post();
                mSharedPreferencesHelper.putString(BaseConstants.LAT, String.valueOf(lat));
                mSharedPreferencesHelper.putString(BaseConstants.LNG, String.valueOf(lon));
                EventBus.getDefault().post(location, "setAddress");

            } else if (location.getLocType() == BDLocation.TypeGpsLocation) {
                // GPS定位成功
                Log.i("baidu_location_result", "Gps location success");
                double lat = location.getLatitude();
                double lon = location.getLongitude();
//                tv_location.setText("lat=" + lat + " lon=" + lon);
//                showMessage("lat=" + lat + " lon" + lon);
                mSharedPreferencesHelper.putString(BaseConstants.LAT, String.valueOf(lat));
                mSharedPreferencesHelper.putString(BaseConstants.LNG, String.valueOf(lon));
                EventBus.getDefault().post(location, "setAddress");


            } else if (location.getLocType() == BDLocation.TypeOffLineLocationFail) {
                // 离线定位失败
                Log.i("baidu_location_result", "offline location fail");
                showMessage("GPS信号弱,定位失败,请到空旷的位置重新定位。");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocationNetworkFail) {
                // 离线定位失败
                Log.i("baidu_location_result", "Network location fail");
                showMessage("网络信号弱,定位失败,请检查网络状态。");
            } else {

                Log.i("baidu_location_result", "location type = " + location.getLocType());
//                showMessage("location type = " + location.getLocType());

            }

        }
    }

}
